<?php

/*
 * Created on May 15, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 * Modify by Khoi Pham
 */

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Product extends MY_Controller {

    function __construct() {

        parent::__construct();

        $this->checkLogin();
        $this->buildMenu();
        $this->load->model('pcategory_model', 'category', true);
        $this->load->model('product_model', 'product', true);
        $this->load->model('upload_files_model', 'file', true);
        $this->load->helper('ckeditor');
        
    }

    function Product() {
        parent::VNT_Controller();
        $this->load->library('xajax', 'category');
        $this->xajax->registerFunction(array('changeBestSell', &$this, 'changeBestSell'));
        $this->xajax->registerFunction(array('changeSpecial', &$this, 'changeSpecial'));
        $this->xajax->registerFunction(array('changeDisplay', &$this, 'changeDisplay'));

        $this->xajax->processRequest();
        $this->xajax_js = $this->xajax->getJavascript($this->base_url . 'js/');
        $this->load->model('product_model', 'product', true);
        $this->load->model('pcategory_model', 'category', true);
        //$cats = $this->category->getAll();
        //if(!is_object( $a[0])) echo '<br><br> 0 Not is an object<br>';
        //if(is_object( $a[1])) echo '<br><br> 1 It is an object<br>';
        $this->checkLogin();
    }

    function changeBestSell($id) {
        $this->load->model('product_model', 'product', true);
        $product = $this->product->getById($id);

        if ($product) {

            $product->best_sell = $product->best_sell == 1 ? 0 : 1;

            $this->product->update($product);

            $objResponse = new xajaxResponse();

            //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

            return $objResponse;
        }
    }

    function changeSpecial($id) {
        $this->load->model('product_model', 'product', true);
        $product = $this->product->getById($id);

        if ($product) {

            $product->special = $product->special == 1 ? 0 : 1;

            $this->product->update($product);

            $objResponse = new xajaxResponse();

            //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

            return $objResponse;
        }
    }

    function changeDisplay($id) {
        $this->load->model('product_model', 'product', true);
        $product = $this->product->getById($id);

        if ($product) {

            $product->active = $product->active == 1 ? 0 : 1;

            $this->product->update($product);

            $objResponse = new xajaxResponse();

            //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

            return $objResponse;
        }
    }

    function index() {
    	//echo getDirByDate(date('Y-m-d H:i:s', time()), PRODUCT_IMAGE_PATH);
        //echo $this->config->item('language');
        //$this->main = '<div> erer erer er </div>';
        //$this->execute();
        //$this->load->view('main', '');
        $this->view();
    }

    function upload_images() {

        $zip = new ZipArchive;
		
        // config for all files in array the same
        $config['upload_path'] = './Data/Images/Product/Tmp/';
        $config['allowed_types'] =  'zip|gif|jpg|png|jpg|jpeg';
        $config['encrypt_name'] = false;
        $config['overwrite'] = true;

        $this->load->library('upload', $config);

        #if (!$this->upload->do_upload()) // default input name userfile[]
        if (!$this->upload->do_upload('files')) { // input array name (type file) without []
            // normal way
            #$error = array('error' => $this->upload->display_errors());
            #$this->load->view('upload_form',$error);
            //$this->view_form_array_files($this->upload->display_errors());
        } else {
            // normal way
            #$data = array('upload_data' => $this->upload->data()); // default all
            #$data = array('upload_data' => $this->upload->data('files'));
            #$this->load->view('upload_success',$data);
            //echo '<pre>'; print_r($this->upload->data()); echo '</pre>'; // default all
            //echo '<pre>';
            //print_r($this->upload->data('files'));
            //echo '</pre>';
            //for($i = 0; $i < count($this->upload->data('files')['file_name']); $i++){
            //echo $this->upload->data('files') . '<br>';
            //echo time() . '<br>';
            //}
            $info = $this->upload->data('files');
            $file_ext = $info['file_ext'];
            $full_path = $info['full_path'];
            //print_r($full_path);
            for ($i = 0; $i < count($file_ext); $i++) {
                if ($file_ext[$i] == '.zip') {
                    //$zip->open("./Data/zip/DATM.zip");
                    //$zip->extractTo("./Data/zip");
                    $zip->open($full_path[$i]);
//echo $config['upload_path'];
                    $zip->extractTo($config['upload_path']);
//echo "<br>my time; " . time() . "<br>";
                    $zip->close();
                }
            }

            $copy_file = array();

            $string = "";
            $fileCount = 0;
            $filePath = $config['upload_path']; # Specify the path you want to look in.
            $dir = opendir($filePath); # Open the path
            while ($file = readdir($dir)) {
                if (eregi(PRODUCT_EXTEND_NAME, $file)) { # Look at only files with a .php extension
                    $copy_file[] = $file;
                }
            }

            for ($i = 0; $i < count($copy_file); $i++) {
                copy($config['upload_path'] . $copy_file[$i], PRODUCT_IMAGE_PATH . $copy_file[$i]);
                /* if(is_file($config['upload_path']. $copy_file[$i]))
                  echo $config['upload_path']. $copy_file[$i] . " is FILE.";
                  else echo $config['upload_path']. $copy_file[$i] . " is FOLDER.";
                 */
                @unlink($config['upload_path'] . $copy_file[$i]);
                //echo " I delete " . $config['upload_path']. $copy_file[$i] . "<br>";
            }

            for ($i = 0; $i < count($full_path); $i++) {
                @unlink($full_path[$i]);
                //echo " I delete " . $config['upload_path']. $copy_file[$i] . "<br>";
            }
        }


        $data = array();

        $data['ddlCategory'] = $this->buidDDProductCategoryList('category', '');
        $data['error_message'] = '';
        //$data['legend_text'] = lang('create_product');
        /* $image_upload = array('error'=> false);
          if(isset($_FILES['file']['tmp_name']) AND strlen($_FILES['file']['tmp_name']) > 0){
          $attach_image = true;
          $image_upload = $this->upload_image('files', PRODUCT_IMAGE_PATH );
          if($image_upload['error'])
          $error_message .= $image_upload['message'];

          }
         */
        $this->main = $this->load->view('admin/product/upload_images', $data, true);
        $this->execute();
    }

    function create() {
        $obj = new stdClass();
         $data['id_product'] = 0;
         $data['code'] = '';
         $data['code_parent'] = '';
         $data['id_pcategory'] = 0;
         $data['code_pcategory'] = '';
         $data['vi_name'] = '';
         $data['en_name'] = '';
         $data['vi_description'] = '123';
         $data['en_description'] = '';
         $data['id_unit'] = 0;
         $data['id_source'] = 0;
         $data['id_provider'] = 0;
         $data['quantity'] = 0;
         $data['price'] = 0;
         $data['active'] = 1;
         $data['special'] = 0;
         $data['best_sell'] = 0;
         $data['sale_off'] = '0%';    
         $data['old_price'] = 0;
         $data['image'] = '';
         $data['images'] = array();
         $data['base_url'] = base_url();

        $data['date_add'] = date('Y-m-d H:i:s', time());
        $data['date_upd'] = date('Y-m-d H:i:s', time());
        $data['upload_dir'] = getDirByDate($data['date_add'], PRODUCT_IMAGE_PATH);
        $this->load->model('unit_model', 'unit', true);
        $this->load->model('source_model', 'source', true);
        $this->load->model('provider_model', 'provider', true);

        $select_unit = new stdClass();
        $select_unit->id = 0;
        $select_unit->vi_name = 'Select';
        $select_unit->en_name = 'Select';

        $select_source = new stdClass();
        $select_source->id = 0;
        $select_source->vi_name = 'Select';
        $select_source->en_name = 'Select';

        $select_provider = new stdClass();
        $select_provider->id_provider = 0;
        $select_provider->vi_name = lang('select_category');
        $select_provider->en_name = lang('select_category');

        //$data['product'] = $obj;
        $data['ddlCategory'] = $this->buidDDProductCategoryList('category', '');
        $data['units'] = array_merge(array($select_unit), $this->unit->getAll());
        $data['sources'] = array_merge(array($select_source), $this->source->getAll()); //print_r($data['units']);
        $data['providers'] = array_merge(array($select_provider), $this->provider->getAll());
        $data['error_message'] = '';
        $data['legend_text'] = lang('create_product') ;
        
        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');


        //$this->template->parse_view('content', 'admin/product/create_product', $data);
       
        $this->template->parse_view('content', 'admin/product/create_product', $data);
        $this->template->render();

        // $this->main = $this->load->view('admin/product/create_product', $data, true);
        // $this->execute();
    }

    function view_file() {
        $data = array();
        $this->main = $this->load->view('admin/product/view_file', $data, true);
        $this->execute();
    }

    function edit($id) {
        $product = $this->product->getById($id);
       // print_r($product); die();
        if (!$product) {
            redirect('admin/product/view');
        }
        
        $this->load->model('unit_model', 'unit', true);
        $this->load->model('source_model', 'source', true);
        $this->load->model('provider_model', 'provider', true);
        $select_unit = new stdClass();
        $select_unit->id = 0;
        $select_unit->vi_name = 'Select';
        $select_unit->en_name = 'Select';

        $select_source = new stdClass();
        $select_source->id = 0;
        $select_source->vi_name = lang('select_category');
        $select_source->en_name = lang('select_category');

        $select_provider = new stdClass();
        $select_provider->id_provider = 0;
        $select_provider->vi_name = lang('select_category');
        $select_provider->en_name = lang('select_category');
        
        $data = $product;
        $data['sale_off'] = ($product['sale_off']*100) . '%';
        $data['ddlCategory'] = $this->buidDDProductCategoryList('category', $product['code_pcategory']); //echo  $product->code_pcategory . 'AAAAAA' . $product->vi_name;
        $data['units'] = array_merge(array($select_unit), $this->unit->getAll());
        $data['sources'] = array_merge(array($select_source), $this->source->getAll()); //print_r($data['units']);
        $data['providers'] = array_merge(array($select_provider), $this->provider->getAll()); //print_r($data['units']);
        $data['error_message'] = '';
        $data['legend_text'] = lang('edit_product');
		$data['base_url'] = base_url();
		$data['upload_dir'] = getDirByDate($data['date_add'], PRODUCT_IMAGE_PATH);
        $data['images'] =  $this->file->getFileByType($id, IMAGE_TYPE, PRODUCT_TYPE);
        //print_r($data['images']);
        if(empty($data['images']))
                $data['images'] = array();
                
        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
        $this->template->parse_view('content', 'admin/product/create_product', $data);
        $this->template->render();
        //$this->main = $this->load->view('admin/product/create_product', $data, true);
        //$this->execute();
    }
    
function do_upload($consultant_id)
    {
        //$this->session->unset_userdata('images');
        $date = $_POST['date_add'];
        $uploaddir = getDirByDate($date, PRODUCT_IMAGE_PATH); //PRODUCT_IMAGE_PATH; //'./uploads/';

        $config['file_name'] =  time(). str_replace(' ', '_', basename($_FILES['uploadfile']['name'])); //date('Y-m-d H:i:s', time()).basename($_FILES['uploadfile']['name']);
        $config['upload_path'] = $uploaddir;
        $config['allowed_types'] = '*'; //'gif|jpg|png|jpeg';
        $config['remove_spaces'] = true;
            //$config['overwrite'] = true;
            $config['max_size'] = 8192; // 8192 kb = 8mb
            
            $result_upload = $this->uploadFile($config);
            if ($result_upload['error']) {

                //$error_message = $result_upload['message'];
               //echo "error";
               // echo $result_upload['message'];
                $data['error'] = true;
                $data['message'] = $result_upload['message'];
                //$data['cname'] = $info['cname'];
                $data['upload_dir'] = $uploaddir;
            } else if($result_upload['error'] == false){
                if($consultant_id == 0){
                    $images = $this->session->userdata('images');

                    $images[]['vi_file_name'] = $config['file_name'];

                    $this->session->set_userdata('images', $images);
                    $data['error'] = false;
                    $data['filename'] = $config['file_name'];
                    $data['image_id'] = time();
                    $data['date'] = $_POST['date_add'];
                    $data['upload_dir'] = $config['upload_path']; //$uploaddir;
                }
                else{

                    $image = new stdClass();
                    $image->item_id = $consultant_id;
                    $image->vi_file_name = $config['file_name'];
                    $image->en_file_name = $config['file_name'];
                    $image->vi_alias = '';
                    $image->en_alias = '';
                    $image->vi_description = '';
                    $image->en_description = '';
                    $image->position = $this->file->getMaxPosition() + 1;
                    $image->file_type = IMAGE_TYPE;
                    $image->item_type = PRODUCT_TYPE; // 2:consultant, 1:portfolio
                    $image->active = 1;
                    $image->add_date = date('Y-m-d H:i:s', time());
                    $image->upd_date = date('Y-m-d H:i:s', time());

                    $image_id = $this->file->create($image);
                    //$this->session->set_userdata('images', $images);
                    $data['error'] = false;
                    $data['filename'] = $config['file_name'];
                    $data['image_id'] = $image_id;
                    $data['upload_dir'] = $uploaddir;
                }

                //echo $config['file_name']; //"success";

            }

            echo json_encode($data);

    }

    function uploadFile($config) {

        $this->load->library('upload', $config);
        $result = array('error' => false);

        if (!$this->upload->do_upload('uploadfile')) {
            $result['message'] = $this->upload->display_errors();
            $result['error'] = true;
        } else {
            $result['upload_data'] = $this->upload->data();
        }

        return $result;
    }
    
    function delete_image(){
        $imageName = $this->input->post('image_name');
        $consultantID = $this->input->post('product_id');
        $result['error'] = false;

        if($consultantID > 0){
            $_resutl = $this->file->deleteByName($imageName);

            $consultant  = $this->product->getById($consultantID);
            if(!empty ($consultant) ){
                if($consultant['image'] == $imageName)
                    $this->product->setImage('', $consultantID);
            }

            if($_resutl){
                 $result['error'] = false;
            }
            else
             $result['error'] = true;



        }
        else{
            $result['error'] = false;
            $images = $this->session->userdata('images');
            for($i = 0; $i < count($images); $i++){
                if($images[$i] == $imageName ){
                    unset($images[$i]);
                    $image_default = $this->session->userdata('image_default');
                    if( $image_default == $imageName)
                        $this->session->unset_userdata('image_default');
                    break;
                }
            }
            $this->session->set_userdata('images', $images);

        }

        @unlink(PRODUCT_IMAGE_PATH.$imageName);

        echo json_encode($result);
    }

    
    function set_image(){
        $imageName = $this->input->post('image_name');
        $consultantID = $this->input->post('product_id');
        if($consultantID > 0){
            $resutl = $this->product->setImage($imageName, $consultantID);
            if($resutl){
                 $result['error'] = false;
            }
             $result['error'] = true;
        }
        else{
            $result['error'] = false;
            $this->session->set_userdata('image_default', $imageName);
        }

         echo json_encode($result);
    }

    function create_from_excel() { //
        $error_message = '';
        if (isset($_FILES['file']['tmp_name'])) {
            $config['upload_path'] = './Data/';
            $config['allowed_types'] = 'xls';
            //$config['overwrite'] = true;
            $config['max_size'] = 8192; // 8192 kb = 8mb
            //$config['max_width']  = '1024';
            //$config['max_height']  = '768';
            //$config['max_filename'] = 50;
            //$config['encrypt_name'] = true;
            //$config['remove_spaces'] = false;
            $result_upload = $this->uploadFile($config);
            if ($result_upload['error']) {

                $error_message = $result_upload['message'];
            } else {

                //if($result_upload['upload_data']['file_type']==)
                //echo $config['upload_path'].$result_upload['upload_data']['file_name'];
                //echo mime_content_type($config['upload_path'].$result_upload['upload_data']['file_name']);

                $this->load->library('excel/spreadsheet_Excel_Reader');

                $data = new Spreadsheet_Excel_Reader();

                $data->setOutputEncoding('utf-8');
                //$data->setOutputEncoding('windows-1258');
                //$data->setOutputEncoding('iso-8859-1');

                $data->read($config['upload_path'] . $result_upload['upload_data']['file_name']);
                if (!isset($data->_ole->error)) {
                    //$data->read('BG MBT 1P 4-2009.xls');
                    //$data->sheets[1]['cells'][2][3];
                    //$data->sheets[SHEET]['cells'][ROW][COLUMN];

                    error_reporting(E_ALL ^ E_NOTICE);
                    //$colspan = 1;
                    //echo "Sheet:".count($data->sheets);
                    //echo "Sheet:".$data->sheets[0]['numCols'];
                    $this->load->model('unit_model', 'unit', true);
                    $this->load->model('source_model', 'source', true);
                    $units = $this->unit->getAll();
                    $tmp = array();
                    for ($i = 0; $i < count($units); $i++) {
                        $tmp[$units[$i]->vi_name] = $units[$i];
                    }
                    $units = $tmp;

                    $sources = $this->source->getAll();
                    $tmp = array();
                    for ($i = 0; $i < count($sources); $i++) {
                        $tmp[$sources[$i]->vi_name] = $sources[$i];
                    }
                    $sources = $tmp;

                    $this->load->model('pcategory_model', 'pcategory', true);
                    $categories = $this->pcategory->getAll();
                    $tmp = array();
                    for ($i = 0; $i < count($categories); $i++) {
                        $tmp[$categories[$i]->code] = $categories[$i];
                    }
                    $categories = $tmp;


                    $objects = array();
                    for ($a = 0; $a < count($data->sheets); $a++) {
                        $sheet_name = $data->boundsheets[$a]['name'];
                        if (!array_key_exists($sheet_name, $categories)) {

                        }
                        for ($i = 11; $i <= $data->sheets[$a]['numRows']; $i++) {
                            //echo "<br>Row:".$data->sheets[0]['numCols'];
                            //if($data->sheets[$a]['numCols'] < 3) break;
                            $obj = new stdClass();
                            //$obj->code = '';
                            $obj->id_pcategory = 0;
                            $obj->code_pcategory = $sheet_name;
                            //$obj->vi_name = '';

                            /* $obj->number_product = 0;
                              $obj->link_rewrite = '';
                              $obj->meta_title = '';
                              $obj->meta_keywords = '';
                              $obj->meta_description = '';
                              $obj->level_depth = 0;
                             */
                            $obj->active = 1;
                            $obj->special = 0;
                            $obj->image = '';

                            $obj->code = trim($data->sheets[$a]['cells'][$i][1]) . '_' . uniqid();
                            //$obj->code_parent = trim($data->sheets[$a]['cells'][$i][2]);
                            $obj->vi_name = trim($data->sheets[$a]['cells'][$i][2]);
                            $obj->en_name = trim($data->sheets[$a]['cells'][$i][2]);
                            $obj->vi_description = '';
                            $obj->en_description = '';
                            $unit_name = trim($data->sheets[$a]['cells'][$i][4]);
                            $source_name = trim($data->sheets[$a]['cells'][$i][3]);
                            //echo $unit_name . '_' . $source_name .'<br>';
                            if (array_key_exists($unit_name, $units)) {
                                $obj->id_unit = $units[$unit_name]->id;
                            } else {

                                $tmp_unit = new stdClass();
                                $tmp_unit->vi_name = $unit_name;
                                $tmp_unit->en_name = $unit_name;
                                $id_unit = $this->unit->insert($tmp_unit);
                                if (!$id_unit > 0)
                                    break;
                                $obj->id_unit = $id_unit;
                                //$units = $this->unit->getAll();
                                $tmp_unit->id = $id_unit;
                                $units[$unit_name] = $tmp_unit;
                                /* $tmp =  array();
                                  for($i = 0; $i < count($units); $i++){
                                  $tmp[$units[$i]->vi_name] = $units[$i];
                                  }
                                  $units = $tmp; */
                            }

                            if (array_key_exists($source_name, $sources)) {
                                $obj->id_source = $sources[$source_name]->id;
                            } else {
                                $tmp_source = new stdClass();
                                $tmp_source->vi_name = $source_name;
                                $tmp_source->en_name = $source_name;
                                $id_source = $this->source->insert($tmp_source);
                                if (!$id_source > 0)
                                    break;
                                $obj->id_source = $id_source;
                                $tmp_source->id = $id_source;
                                $sources[$source_name] = $tmp_source;

                                /* $tmp =  array();
                                  for($i = 0; $i < count($sources); $i++){
                                  $tmp[$sources[$i]->vi_name] = $sources[$i];
                                  }
                                  $sources = 	$tmp; */
                            }

                            $obj->quantity = trim($data->sheets[$a]['cells'][$i][4]);
                            $obj->price = trim($data->sheets[$a]['cells'][$i][5]);
                            $obj->date_add = date('Y-m-d H:i:s', time());
                            $obj->date_upd = date('Y-m-d H:i:s', time());

                            if ($obj->code != '' AND $obj->code != null AND $obj->vi_name != '' AND $obj->vi_name != null)
                                $objects[] = $obj;
                            //	break;
                            //if($obj->code!='' AND $obj->vi_name!='')
                            //$objects[] = $obj;

                            /*
                              for ($j = 1; $j <= $data->sheets[$a]['numCols']; $j++) {
                              $value = $data->sheets[$a]['cells'][$i][$j];
                              $colspan = $data->sheets[$a]['cellsInfo'][$i][$j]['colspan'];
                              if($colspan){
                              //echo "<td colspan='$colspan' style='border-bottom:1px solid black;'>". $value . "</td>\n";
                              }
                              else{
                              if(!$value) $value = "&nbsp;";
                              //echo "<td style='border-bottom:1px solid black;'>". $value . "</td>\n";
                              $colspan = 1;
                              }

                              } // for column
                             */
                        } //for row
                    } // for count sheet
                    if (count($objects) > 0) {  //print_r($objects);
                        $result = $this->product->create($objects);
                        $this->product->update_code_category();
                        @unlink($config['upload_path'] . $result_upload['upload_data']['file_name']);
                        //redirect('admin/pcategory');
                        //return;
                    }
                } //if
                else {
                    $error_message .= 'The filename ' . $result_upload['upload_data']['file_name'] . ' is not readable';
                }
            }
        }
        $data = array();
        $data['error_message'] = '<div style="color:red">' . $error_message . '</div>';
        $this->main = $this->load->view('admin/product/form_upload', $data, true);
        $this->execute();
    }

    function create_from_xml() {
        $data = array();
        //$data['error_message'] = '';
        $data['ddlCategory'] = $this->buidDDProductCategoryList('category', '');
        $data['error_message'] = ''; //'<div style="color:red">'.$error_message . '</div>';
        $this->main = $this->load->view('admin/product/form_upload_xml', $data, true);
        $this->execute();
    }

    /*
    function uploadFile($config) {

        $this->load->library('upload', $config);
        $result = array('error' => false);

        if (!$this->upload->do_upload('file')) {
            $result['message'] = $this->upload->display_errors();
            $result['error'] = true;
        } else {
            $result['upload_data'] = $this->upload->data();
        }

        return $result;
    }
    */

    function view() {

        $this->load->library('pagination');

        $code_category = $this->uri->segment(4, -1);
        // echo '<br>' . $code_category . '<br>';
        $category = $this->category->getByCode($code_category);

        if ($category)
            $category = $category->id_pcategory;
        else
            $category = -1;

        $page = (int) $this->uri->segment(5);
        //$base_url = $this->base_url . 'admin/product/view/' . $category . '/';
        $base_url = site_url ( 'admin/product/view/' . $code_category . '/');
        $total_rows = $this->product->countAll($category);
        $per_page = NUMBER_RECORD_PER_PRODUCT_PAGE;
        $uri_segment = 5;


        pagination($base_url, $total_rows, $per_page, $uri_segment);


        $items = '';
        $products = $this->product->getAll($page, NUMBER_RECORD_PER_PRODUCT_PAGE, $category);

        if ($page > 0 AND count($products) == 0) {
            redirect('admin/contact/view/' . ($page - NUMBER_RECORD_PER_PAGE));
            return;
        }

        $data = array();
        $data['rows'] = $products;
        // print_r($products);
		//$data['upload_dir'] = getDirByDate($data['date_add'], PRODUCT_IMAGE_PATH); ;
        $data['ddlCategory'] = $this->buidDDProductCategoryList('category', $code_category, 'onchange="loadProduct()"');
        //$this->main = eval ($this->loadTemplate('admin/product/product_list.tpl'));
        //$this->main = $this->load->view('admin/product/product_list', $data, true);
        //$this->execute();
        $this->template->parse_view('content', 'admin/product/product_list', $data);
        $this->template->render();
    }

    function loadItems() {
        /* $item = '';
          $items = $this->pcategory->getAll();
          $this->setTemplate(array ('admin/pcategory/pcategory_item.tpl'));
          for($i = 0; $i < count($items); $i++){
          $id = $items[$i]->id_pcategory;
          $name = $items[$i]->vi_name;
          $description = $items[$i]->vi_description;
          $item .= eval ($this->loadTemplate('admin/pcategory/pcategory_item.tpl'));
          }

          return $item; */
    }

    function loadNewsItems($categories = null, $parent = 0, $track = array(), $style = 1, $index = 1) {
        $items = '';
        if (!$categories) {
            $categories = $this->category->getAll();
        }
        $tmp = array();
        for ($i = 0; $i < count($categories); $i++) {
            $category = $categories[$i];
            $tmp[$category->category_parent_id][$category->category_id] = $category;
        }

        if (isset($tmp[$parent])) {
            $num_record = count($tmp[$parent]);
            foreach ($tmp[$parent] as $k => $v) {
                $parent = $v->category_id;
                $category_id = $v->category_id;
                $category_name = $v->name_vi;
                if ($index % 2 == 0)
                    $class = 'class="bg"';
                else
                    $class = '';
                $items .= eval($this->loadTemplate('news_categories_item.tpl'));
                //if(in_array($v->category_id, $track))
                $index++;
                $items .=$this->loadProductItems($categories, $parent, $track, $style + 1, $index);
            }

            /* for($j = 1; $j <= count($tmp[$parent]); $j++){
              if(isset($tmp[$parent][$j])){
              $category = $tmp[$parent][$j];
              $parent = $category->category_id;
              $category_id = $category->category_id;
              $category_name = $category->name;
              if($index%2 == 0) $class = 'class="bg"';
              else $class = '';
              $items .= eval($this->loadTemplate('product_categories_item.tpl'));
              //if(in_array($v->category_id, $track))
              $index++;
              $items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
              }
              } */
        }
        //print_r($categories);
        return $items;
    }

    function view_product_category() {
        $this->load->model('product_category_model', 'category', true);
        $categories = $this->category->getAll();
        $items = $this->loadProductItems($categories);
        $content = eval($this->loadTemplate('product_categories.tpl'));
        $this->execute($content);
    }

    function loadProductItems($categories = null, $parent = 0, $track = array(), $style = 1, $index = 1) {
        $items = '';
        if (!$categories) {
            $categories = $this->category->getAll();
        }
        $tmp = array();
        for ($i = 0; $i < count($categories); $i++) {
            $category = $categories[$i];
            $tmp[$category->category_parent_id][$category->category_id] = $category;
        }


        if (isset($tmp[$parent])) {
            $num_record = count($tmp[$parent]);
            foreach ($tmp[$parent] as $k => $v) {
                $parent = $v->category_id;
                $category_id = $v->category_id;
                $category_name = $v->name_vi;
                if ($index % 2 == 0)
                    $class = 'class="bg"';
                else
                    $class = '';
                $items .= eval($this->loadTemplate('product_categories_item.tpl'));
                //if(in_array($v->category_id, $track))
                $index++;
                $items .=$this->loadProductItems($categories, $parent, $track, $style + 1, $index);
            }

            /* for($j = 1; $j <= count($tmp[$parent]); $j++){
              if(isset($tmp[$parent][$j])){
              $category = $tmp[$parent][$j];
              $parent = $category->category_id;
              $category_id = $category->category_id;
              $category_name = $category->name;
              if($index%2 == 0) $class = 'class="bg"';
              else $class = '';
              $items .= eval($this->loadTemplate('product_categories_item.tpl'));
              //if(in_array($v->category_id, $track))
              $index++;
              $items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
              }
              } */
        }
        //print_r($categories);
        return $items;
    }

    function buidDDProductCategoryList($name, $default, $action = '') {
        $this->load->model('pcategory_model', 'pcategory', true);
        $categories = $this->pcategory->getAll();
        //$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
        $space = '';
        //$name = 'Parent';
        $value = '';
        $selected = '';
        $space = '';
        $label = lang('category');
        $class = '';

        $style = '';

        $tmp = array();
        for ($i = 0; $i < count($categories); $i++) {
            $category = $categories[$i];
            //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
            $tmp[$category->code_parent][$category->code] = $category;
        }

        // $options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($tmp/* $categories */, '', $default);
        // return eval($this->loadTemplate('admin/ddl.tpl'));
        //$options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($tmp/*$categories*/, '', $default);
        $options = $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true) . $this->getCategoryOption($tmp/* $categories */, '', $default);
        $data = array();
        $data['name'] = $name;
        $data['style'] = $style;
        $data['class'] = $class;
        $data['action'] = $action;
        $data['options'] = $options;
        return $this->load->view('admin/select', $data, true);
        //return eval($this->loadTemplate('admin/ddl.tpl'));
    }

    function buidDDNewsCategoryList($name, $default) {
        $this->load->model('news_category_model', 'category', true);
        $categories = $this->category->getAll();
        $this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
        $space = '';
        $name = 'Parent';
        $value = 0;
        $selected = '';
        $options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($categories, 0, $default);
        return eval($this->loadTemplate('admin/ddl.tpl'));
    }

    function getCategoryOption($tmp/* $categories */, $parent = ''/* 0 */, $default = ''/* 0 */, $space = '&nbsp;') {
        $items = '';

        if (isset($tmp[$parent])) {
            $num_record = count($tmp[$parent]);
            foreach ($tmp[$parent] as $k => $v) {
                //$parent = $v->id_pcategory;
                //$value = $v->id_pcategory;
                //echo '<br>\n'.$parent . '_\n';
                $parent = $v->code;
                $value = $v->code;
                $label = $v->vi_name;
                $selected = '';
                if ($value == $default)
                    $selected = 'selected';

                $items .= $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true);
                $items .=$this->getCategoryOption($tmp/* $categories */, $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');

                //$items .= eval($this->loadTemplate('admin/option_ddl.tpl'));
                //$items .=$this->getCategoryOption($tmp/* $categories */, $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            }
        }

        return $items;
    }

    function save() {
        
        $txtID = (int) trim($this->input->post('txtID'));
        //$txtCode = preg_replace("/[".VALID_CHARACTERS."]/", "", trim($this->input->post('txtCode')));
		$data = array();
        if ($txtID > 0){
            $data = $this->product->getById($txtID);
         	if (empty($data)) {
                redirect('admin/product/view');
                return;
            }

            //$data = $news;
            $data['images'] =  $this->file->getFileByType($txtID, IMAGE_TYPE, PRODUCT_TYPE);   
        }
        else {
            $data['id_product'] = 0;
            $data['code'] = '';
            $data['image'] = '';
            
            $images = $this->session->userdata('images');
            if(empty ($images))
                $images = array();
            $data['images'] = $images;
            $image = $this->session->userdata('image_default');
            if(empty ($image))
                $image = '';
            $data['image'] = $image;
        }

        $data['code_pcategory'] = trim($this->input->post('category'));

        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');

        if ((trim($this->input->post('txtCode')) != $data['code'] && $txtID > 0) || $txtID == 0) {
            $this->form_validation->set_rules('txtCode', 'lang:product_code', 'required|min_length[2]|max_length[120]|callback_code_check');
            //echo $txtCode.' '.$category->code; return;
        }else
            $this->form_validation->set_rules('txtCode', 'lang:product_code', 'required|min_length[2]|max_length[120]');
        //$this->form_validation->set_rules('parent', 'lang:parent_code', 'required|min_length[2]|max_length[120]');
        $this->form_validation->set_rules('txtViName', 'lang:vi_name', 'required|min_length[2]|max_length[120]');
        $this->form_validation->set_rules('txtEnName', 'lang:en_name', 'required|min_length[2]|max_length[120]');

        $this->form_validation->set_rules('unit', 'lang:unit', 'required|min_length[2]|max_length[120]');
        $this->form_validation->set_rules('source', 'lang:source', 'required');
        $this->form_validation->set_rules('provider', 'lang:provider', 'required');

        $this->form_validation->set_rules('category', 'lang:category', 'callback_category_check');
        //if($txtLinkRewrite!='' AND $txtLinkRewrite!=$category->link_rewrite)
        //$this->form_validation->set_rules('txtLinkRewrite', 'lang:friendly_url', 'callback_friendly_url_check');
        /* $this->form_validation->set_rules('password', 'Password', 'required');
          $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
          $this->form_validation->set_rules('email', 'Email', 'required');
         */

        if (empty($data['id_product']) && $txtID > 0) {
            redirect('admin/product/view');
            return;
        }

        $data['code'] = trim($this->input->post('txtCode')); //preg_replace("/[".VALID_CHARACTERS."]/", "", trim($this->input->post('txtCode'))); //preg_replace('/[";<>&*~|#] /', '', trim($this->input->post('txtCode'))) ;

        $this->load->model('pcategory_model', 'pcategory', true);
        $category = $this->pcategory->getByCode(trim($this->input->post('category')));
        if ($category) {
            $data['code_pcategory'] = $category['code'];
            $data['id_pcategory'] = $category['id_pcategory'];
        }

        $data['vi_name'] = trim($this->input->post('txtViName'));
        $data['en_name'] = trim($this->input->post('txtEnName'));
        $data['vi_description'] = trim($this->input->post('txtViDescription'));
        $data['en_description'] = trim($this->input->post('txtEnDescription'));
        $data['id_unit'] = trim($this->input->post('unit'));
        $data['id_source'] = trim($this->input->post('source'));
        $data['id_provider'] = trim($this->input->post('provider'));
        $data['quantity'] = trim($this->input->post('txtQuantity'));
        $data['price'] = trim($this->input->post('txtPrice'));
        $data['special'] = (int) $this->input->post('special');
        $data['best_sell'] = (int) $this->input->post('bestSell');
        $data['sale_off'] = doubleval( str_replace('%', '', $this->input->post('txtSaleOff')))/100;
        
        $data['active'] = (int) $this->input->post('active');
       
        $data['base_url'] = base_url();
        
        //$data['image'] = '';
        $data['date_add'] = trim($this->input->post('txtDateAdd'));
        $data['date_upd'] = date('Y-m-d H:i:s', time());
        $error_message = ''; // $this->loadErrorMessage('Thong diep loi.');
        $category_parent = ''; //$this->buidDDNewsCategoryList('ddlParentCategory', 0);
        //print_r($_POST);
        $attach_image = false;
        $image_upload = array('error' => false);
        if (isset($_FILES['file']['tmp_name']) AND strlen($_FILES['file']['tmp_name']) > 0) {
            $attach_image = true;
            $image_upload = $this->upload_image('file', PRODUCT_IMAGE_PATH /* './Data/Images/Product/' */);
            if ($image_upload['error'])
                $error_message .= $image_upload['message'];
        }

        if ($this->form_validation->run() == FALSE /*&& ($attach_image == true AND $image_upload['error'] == true)*/) {

            $error_message = validation_errors() . '<br>' . $error_message;
            //$code = uniqid();
            //$this->session->set_userdata('code', $code);
            $this->load->model('unit_model', 'unit', true);
            $this->load->model('source_model', 'source', true);
            $this->load->model('provider_model', 'provider', true);

            $select_unit = new stdClass();
            $select_unit->id = 0;
            $select_unit->vi_name = lang('select_category');
            $select_unit->en_name = lang('select_category');

            $select_source = new stdClass();
            $select_source->id = 0;
            $select_source->vi_name = lang('select_source');
            $select_source->en_name = lang('select_source');

            $select_provider = new stdClass();
            $select_provider->id_provider = 0;
            $select_provider->vi_name = lang('select_source');
            $select_provider->en_name = lang('select_source');

           // $data = array();
            //$data['product'] = $product;
            $data['sale_off'] = $this->input->post('txtSaleOff');
            $data['old_price'] = $this->input->post('txtOldPrice');
            $data['ddlCategory'] = $this->buidDDProductCategoryList('category', $data['code_pcategory']);
            $data['units'] = array_merge(array($select_unit), $this->unit->getAll());
            $data['sources'] = array_merge(array($select_source), $this->source->getAll());
            $data['providers'] = array_merge(array($select_provider), $this->provider->getAll());
            $data['error_message'] = '<div style="color:red">' . $error_message . '</div>';
            //if()
            $data['legend_text'] = $txtID > 0 ? lang('edit_product') : lang('create_product');
            //$this->main = $this->load->view('admin/product/create_product', $data, true);
            //$this->execute();
            $this->load->library('ckeditor');
            $this->load->library('ckFinder');
            $this->template->add_js('asset/ckeditor/ckeditor.js');
            $this->template->add_js('asset/ckfinder/ckfinder.js');
            //configure base path of ckeditor folder
            $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
            $this->ckeditor->config['toolbar'] = 'Full';
            $this->ckeditor->config['language'] = 'en';
            //configure ckfinder with ckeditor config
            $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');

            $this->template->parse_view('content', 'admin/product/create_product', $data);
            $this->template->render();
            return;
        } else {
        	$data['old_price'] = $this->input->post('txtOldPrice');
            //$this->load->model('pcategory_model', 'pcategory', true);
            //$cat = $this->pcategory->getByCode($data['code_pcategory);
            //$data['id_pcategory = $cat->id_pcategory;
            if ($attach_image) {
                $file_path = PRODUCT_IMAGE_PATH . $image_upload['upload_data']['file_name'];
                if ($txtID > 0 && $data['image'] != $file_path) {
                    @unlink(PRODUCT_IMAGE_PATH.$data['image']);
                }
			
                $data['image'] = $image_upload['upload_data']['file_name']; //$file_path;
            }
			
            $result = 0;
            $insert_id = 0;
            
            if ($txtID > 0) {
                $result = $this->product->update($data);
                
            } else {
                $data['number_product'] = 0;
                $data['level_depth'] = 0;
                //$data['date_add'] = date('Y-m-d H:i:s', time());
                $txtID = $insert_id = $result = $this->product->create($data);
            }
			
            
        $images = $this->session->userdata('images');

            if ($txtID > 0) {
                if(!empty($images) && count($images) > 0){

                $_images = array();
                for ($i = 0; $i < count($images); $i++) {
                    $name_image = $images[$i];
                    $image = new stdClass();
                    $image->item_id = $txtID;
                    $image->vi_file_name = $name_image['vi_file_name'];
                    $image->en_file_name = $name_image['vi_file_name'];
                    $image->vi_alias = '';
                    $image->en_alias = '';
                    $image->vi_description = '';
                    $image->en_description = '';
                    $image->position = $this->file->getMaxPosition() + 1;
                    $image->file_type = IMAGE_TYPE;
                    $image->item_type = PRODUCT_TYPE;
                    $image->active = 1;
                    $image->add_date = date('Y-m-d H:i:s', time());
                    $image->upd_date = date('Y-m-d H:i:s', time());

                    $_images[] = $image;


                    }

                if (count($_images) > 0) {

                    $this->file->create($_images);

                }
                $this->session->unset_userdata('images');
                }
                
            }
            
            
            //$this->product->update_code_category();

            if (isset($_SESSION['fck_images']) AND count($_SESSION['fck_images']) > 0) {
                if ($txtID > 0)
                    $product_id = $txtID;
                else
                    $product_id = $result;
                $fck_files = array();
                for ($i = 0; $i < count($_SESSION['fck_images']); $i++) {
                    //$file_url = '.'.substr($_SESSION['fck_images'][$i], strlen('/caney/' /*Replace*/)-1);
                    $file_url = '.' . $_SESSION['fck_images'][$i]; // FOR REAL HOST Ex: http://localhost
                    //$file_url = '.'.$_SESSION['fck_images'][$i]; // FOR localhsot  Ex: http://localhost/ten_cua_website
                    if (file_exists($file_url)) {
                        $fck_file = new stdClass();
                        $fck_file->file_url = $file_url;
                        $fck_file->item_id = $product_id;
                        $fck_file->type = 'product';
                        $fck_files[] = $fck_file;
                    }
                }

                if (count($fck_files) > 0) {
                    $this->load->model('fck_files_model', 'fckfile', true);
                    $this->fckfile->create($fck_files);
                    $_SESSION['fck_images'] = null;
                }

                //print_r($_SESSION['fck_images']);
            }

            redirect('admin/product/view');
            //redirect($this->session->userdata('his_adm'));
        }
    }

    function upload_image($field_name, $path, $allowed_types = '') {
        $result = array();
        $config['upload_path'] = $path; //'./Data/Images/';
        if ($allowed_types == '')
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
        else
            $config['allowed_types'] = $allowed_types;
        //$config['max_size']	= '1000';
        //$config['max_width']  = '1024';
        //$config['max_height']  = '768';
        $config['overwrite'] = true;


        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($field_name)) {
            //$error = array('error' => $this->upload->display_errors());
            $result['error'] = true;
            $result['message'] = $this->upload->display_errors();
            //$this->load->view('upload_form', $error);
        } else {
            //$data = array('upload_data' => $this->upload->data());
            $result['error'] = false;
            $result['upload_data'] = $this->upload->data();
        }

        return $result;
    }

    function code_check($code) {
        $result = $this->product->getByCode($code);
        if ($result != null) {
            $this->form_validation->set_message('code_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function friendly_url_check($url) {
        $result = $this->pcategory->getByLinkRewrite($url);
        if ($result != null) {
            $this->form_validation->set_message('friendly_url_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function testGetFile() {
        $config = array(
            'allowed' => array('JPEG', 'jpg', 'PNG', 'png', 'GIF', 'gif'),
            'max_size' => 1024000000 /* 1Mb */
        );

        $result = getFile($config, 'Data', 'http://images8.dantri.com.vn/ThumbImages/Uploaded/2009/05/08/lut080520094_327.jpg');

        if (!$result['error'])
            echo 'Get file success.';
        else
            echo $result['message'];
    }

    function delete() {
        //print_r($this->input->post('categoryBox'));
        //return;
        $id = intval($this->uri->segment(4));
        $ids = array();
        if ($id > 0) {
            $ids[] = $id;
            //$this->product->delete($id);
        } else {
            if (count($this->input->post('categoryBox')) > 0) {
                $ids = $this->input->post('categoryBox');
                //print_r($_POST);
                //return;
            } else {
                redirect($this->session->userdata('his_adm'));
                return;
            }
        }

        if (count($ids)) {
            // Xoa file anh chinh:
            $this->load->model('fck_files_model', 'fckfile', true);
            $products = $this->product->getAllByIds($ids);
            $main_images = array();
            $fck_images = array();
            $fck_images_id = array();
            if (count($products) > 0) {
                for ($i = 0; $i < count($products); $i++) {
                    $main_images[] = PRODUCT_IMAGE_PATH.$products[$i]->image;
                    $_fck_files = $this->fckfile->getAllByItemId($products[$i]->id_product, 'product');
                    if (count($_fck_files) > 0) {
                        for ($j = 0; $j < count($_fck_files); $j++) {
                            $fck_images[] = $_fck_files[$j]->file_url;
                            $fck_images_id[] = $_fck_files[$j]->id;
                        }
                    }
                }
            }


            //Xoa san pham
            $result = $this->product->delete($ids);
            if ($result) {
                if (count($main_images) > 0) {
                    for ($i = 0; $i < count($main_images); $i++) {
                        @unlink($main_images[$i]);
                    }
                }

                if (count($fck_images) > 0) {
                    for ($i = 0; $i < count($fck_images); $i++) {
                        @unlink($fck_images[$i]);
                    }
                }
                if (count($fck_images_id))
                    $this->fckfile->delete($fck_images_id);
            }
        }

        redirect($this->session->userdata('his_adm'));
        //redirect('admin/product');
    }

    function create_product_from_xml() {

        $this->load->library('form_validation');

        $this->form_validation->set_rules('category', 'category', 'callback_category_check');

        $image_upload = $this->upload_image('file', TMP_PATH /* './Data/Tmp/' */, 'xml');

        $error_message = ''; //$image_upload['message'];

        if ($this->form_validation->run() == FALSE OR $image_upload['error'] == true) {
            $data = array();
            //$data['error_message'] = '';
            if ($image_upload['error'])
                $error_message = $image_upload['message'];
            $data['ddlCategory'] = $this->buidDDProductCategoryList('category', '');
            $data['error_message'] = '<div style="color:red">' . validation_errors() . $error_message . '</div>';
            $this->main = $this->load->view('admin/product/form_upload_xml', $data, true);
            $this->execute();
            return;
        }

        $provider_error = array();
        $unit_error = array();
        $duplicate_error = array();
        $data_insert = array();
        $data_update = array();

        $code_pcategory = trim($this->input->post('category'));
        $file_path = TMP_PATH . $image_upload['upload_data']['file_name'];

        if (/* isset($_FILES['file']['tmp_name']) */ file_exists($file_path)) {
            $this->load->helper('text');
            $doc = new DOMDocument();
            $doc->load($file_path /* './Data/Demo_demo.xml' */);
            $sheets = $doc->getElementsByTagName("Worksheet");
            $data = array();

            //$categories2 = $this->category->getAll();
            $this->load->model('pcategory_model', 'pcategory', true);
            $categories = $categories2 = $this->pcategory->getAll();

            $tmp = array();
            for ($i = 0; $i < count($categories2); $i++) {
                $category = $categories2[$i];
                //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
                $tmp[$category->code_parent][$category->code] = $category;
            }

            // Fillter sheets:
            $codes_cat = $this->helpViewProduct($tmp, $code_pcategory);
            $codes_cat[] = $this->db->escape($code_pcategory);
            // Kiem tra Ma danh muc san pham (ten sheet)  co trong database hay ko:
            $pcategory_invalid = array();
            foreach ($sheets as $sheet) {
                $name_sheet = $sheet->getAttribute('ss:Name');
                if (substr(trim($name_sheet), 0, 4) == 'GET-') {
                    $data[] = $sheet;
                    $sheet_name = $sheet->getAttribute('ss:Name');
                    $sheet_name = substr($sheet_name, 4, strlen($sheet_name) - 4); // 4 = strlen('GET-')
                    $sheet_name = preg_replace("/[" . VALID_CHARACTERS . "]/", "", $sheet_name);
                    // echo "SHEET1 = " .$sheet_name1 . "     ---- SHEETname=" . $sheet_name . "<br>";
                    if (!in_array($this->db->escape($code_pcategory . '-' . $sheet_name), $codes_cat)) {
                        $pcategory_invalid[] = $code_pcategory . '-' . $sheet_name;
                    }
                }
            }

            if (count($pcategory_invalid) > 0) {
                /* $m =  'Danh muc '. implode(',', $pcategory_invalid) . ' trong file du lieu khong ton tai trong database hoac khong phu hop voi danh muc <strong>'.$code_pcategory.'</strong>.<br>';

                  $data['ddlCategory'] = $this->buidDDProductCategoryList('category', '');
                  $data['error_message'] = '<div style="color:red">'. $m . '</div>';
                  $this->main = $this->load->view('admin/product/form_upload_xml', $data, true);
                  $this->execute();
                  return; */
                $objects = array();
                for ($i = 0; $i < count($pcategory_invalid); $i++) {
                    $obj = new stdClass();
                    $obj->id_parent_pcategory = 0;
                    //$obj->vi_name = '';
                    //$obj->en_name = '';
                    $obj->vi_description = '';
                    $obj->en_description = '';
                    $obj->number_product = 0;
                    $obj->link_rewrite = '';
                    $obj->meta_title = '';
                    $obj->meta_keywords = '';
                    $obj->meta_description = '';
                    $obj->level_depth = 0;
                    $obj->active = 1;
                    $obj->image = '';
                    $obj->module = PRODUCTS_PAGE;
                    $obj->date_add = date('Y-m-d H:i:s', time());
                    $obj->date_upd = date('Y-m-d H:i:s', time());

                    $obj->code = $pcategory_invalid[$i];
                    $obj->code_parent = $code_pcategory;
                    $obj->vi_name = $pcategory_invalid[$i];
                    $obj->en_name = $pcategory_invalid[$i];
                    //if($obj->code!='' AND $obj->code!=null AND $obj->vi_name!='' AND $obj->vi_name!=null)
                    $objects[] = $obj;
                }

                if (count($objects) > 0) {
                    $result = $this->pcategory->create($objects);
                    if ($result) {
                        $this->pcategory->updateParentId();
                    }
                }
            }

            // end fillter sheet.

            $this->load->model('unit_model', 'unit', true);
            $units = $this->unit->getAll();
            $tmp = array();
            for ($i = 0; $i < count($units); $i++) {
                $tmp[trim($units[$i]->vi_name)] = $units[$i];
            }
            $units = $tmp;


            $this->load->model('source_model', 'source', true);
            $sources = $this->source->getAll();
            $tmp = array();
            for ($i = 0; $i < count($sources); $i++) {
                $tmp[trim($sources[$i]->vi_name)] = $sources[$i];
            }
            $sources = $tmp;
            //print_r($sources);

            $this->load->model('provider_model', 'provider', true);
            $providers = $this->provider->getAll();
            $tmp = array();
            for ($i = 0; $i < count($providers); $i++) {
                $tmp[trim($providers[$i]->vi_name)] = $providers[$i];
            }
            $providers = $tmp;
            //print_r($providers);


            $tmp = array();
            for ($i = 0; $i < count($categories); $i++) {
                $tmp[$categories[$i]->code] = $categories[$i];
            }
            $categories = $tmp;

            $this->load->model('product_model', 'product', true);
            $products = $this->product->getAllByCodes($codes_cat);
            $tmp = array();
            for ($i = 0; $i < count($products); $i++) {
                $product = $products[$i];
                //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
                $tmp[trim(strtolower($product->code))] = $product;
                //$tmp[] = trim($product->code);
            }
            $products = $tmp;
            //print_r($products);

            for ($i = 0; $i < count($data); $i++) {
                $sheet = $data[$i];
                $sheet_name = $sheet->getAttribute('ss:Name');
                $sheet_name = substr($sheet_name, 4, strlen($sheet_name) - 4);
                $sheet_name = preg_replace("/[" . VALID_CHARACTERS . "]/", "", $sheet_name);

                $rows = $sheet->getElementsByTagName('Row');
                $index_row = 0;
                $start_row = 11;
                $provider_name = '';
                foreach ($rows as $row) {
                    $code = "";
                    $middle = "";
                    $last = "";

                    $index = 1;

                    $cells = $row->getElementsByTagName('Cell');

                    if ($cells->item(0)
                            AND $cells->item(1)
                            AND $cells->item(2)
                            AND $cells->item(3)
                            AND $cells->item(4)
                            AND $cells->item(5)
                            AND $cells->item(6)
                            AND $cells->item(7)
                            AND $cells->item(8)
                            AND $cells->item(0)->nodeValue != ''
                            AND $cells->item(1)->nodeValue != ''
                            AND $cells->item(2)->nodeValue != ''
                            AND $cells->item(3)->nodeValue != ''
                            AND $cells->item(4)->nodeValue != ''
                            AND $cells->item(5)->nodeValue != ''
                            AND $cells->item(6)->nodeValue != ''
                            AND $cells->item(7)->nodeValue != ''
                            AND $cells->item(8)->nodeValue != ''
                            AND $index_row >= $start_row
                    ) {

                        // start create product object:
                        $obj = new stdClass();
                        //$obj->code = '';
                        $obj->id_pcategory = 0;
                        $obj->code_pcategory = $code_pcategory . '-' . $sheet_name;

                        $obj->active = 1;
                        $obj->special = 0;
                        $obj->best_sell = 0;
                        $obj->code = trim($cells->item(1)->nodeValue);
                        $obj->vi_name = trim($cells->item(3)->nodeValue);
                        $obj->en_name = trim($cells->item(3)->nodeValue);
                        $obj->vi_description = trim($cells->item(2)->nodeValue);
                        $obj->en_description = trim($cells->item(2)->nodeValue);
                        $unit_name = trim($cells->item(6)->nodeValue);
                        $source_name = trim($cells->item(5)->nodeValue);
                        //$provider_name = trim($cells->item(3)->nodeValue);
                        //echo $unit_name . '_' . $source_name .'<br>';
                        if (array_key_exists($unit_name, $units)) {
                            $obj->id_unit = $units[$unit_name]->id;
                        } else {

                            $tmp_unit = new stdClass();
                            $tmp_unit->vi_name = $unit_name;
                            $tmp_unit->en_name = $unit_name;
                            $id_unit = $this->unit->insert($tmp_unit);
                            if (!$id_unit)
                                break;
                            $obj->id_unit = $id_unit;
                            //$units = $this->unit->getAll();
                            $tmp_unit->id = $id_unit;
                            $units[$unit_name] = $tmp_unit;
                            /* $tmp =  array();
                              for($i = 0; $i < count($units); $i++){
                              $tmp[$units[$i]->vi_name] = $units[$i];
                              }
                              $units = $tmp; */
                        }


                        if (array_key_exists(($source_name), $sources)) {
                            $obj->id_source = $sources[$source_name]->id;
                        } else {
                            $obj->id_source = 0;

                            $tmp_source = new stdClass();
                            $this->source->vi_name = $source_name;
                            $this->source->en_name = $source_name;
                            $id_source = $this->source->insert($tmp_source);
                            if (!$id_source > 0) {
                                $index_row++;
                                continue;
                            }
                            $obj->id_source = $id_source;
                            $tmp_source->id = $id_source;
                            $sources[$source_name] = $tmp_source;
                        }

                        $provider_name = trim($cells->item(4)->nodeValue);

                        if (array_key_exists($provider_name, $providers)) {
                            $obj->id_provider = $providers[$provider_name]->id_provider;
                        } else {
                            //$tmp_provider = new stdClass();
                            $this->provider->vi_name = $provider_name;
                            $this->provider->en_name = $provider_name;
                            $this->provider->order_view = $this->provider->getMaxPosition() + 1;
                            $id_provider = $this->provider->insert();
                            $this->provider->id_provider = $id_provider;
                            $obj->id_provider = $id_provider;
                            $providers[$provider_name] = $this->provider;
                            //$index_row++;
                            //continue;
                            //$provider_error[] = $provider_name;
                        }



                        $obj->quantity = trim($cells->item(7)->nodeValue);
                        $obj->price = trim($cells->item(8)->nodeValue);
                        $obj->image = PRODUCT_IMAGE_PATH . $obj->code . PRODUCT_IMAGE_EXT;
                        $obj->date_add = date('Y-m-d H:i:s', time());
                        $obj->date_upd = date('Y-m-d H:i:s', time());


                        //if($obj->code!='' AND $obj->code!=null AND $obj->vi_name!='' AND $obj->vi_name!=null)
                        //	$objects[] = $obj;

                        if (array_key_exists(trim(strtolower($obj->code)), $products)) {
                            if (array_key_exists(trim(strtolower($obj->code)), $data_update)) {
                                $duplicate_error[] = $obj->code;
                            }
                            else
                                $data_update[trim(strtolower($obj->code))] = $obj;
                        }
                        else {
                            if (array_key_exists(trim(strtolower($obj->code)), $data_insert)) {
                                $duplicate_error[] = $obj->code;
                            }
                            else
                                $data_insert[trim(strtolower($obj->code))] = $obj;
                        }

                        /*
                          if(in_array(trim($obj->code), $products)){
                          //if()
                          $data_update[trim($obj->code)] = $obj;
                          }
                          else{
                          $data_insert[trim($obj->code)] = $obj;
                          }
                         */
                        // end create product object
                    }
                    elseif ($cells->item(0) AND $cells->item(1) == null AND $cells->item(2) == null AND $cells->item(3) == null AND $cells->item(4) == null AND $cells->item(5) == null AND $cells->item(6) == null AND $cells->item(7) == null AND $cells->item(8) == null) {
                        if (array_key_exists(trim(($cells->item(0)->nodeValue)), $providers)) {
                            //$provider_name = trim($cells->item(0)->nodeValue);
                        } else {
                            $index_row++;
                            continue;
                        }
                    }
                    $index_row++;
                }
            }
        } else {

        }

        if (count($data_insert) > 0) {  //print_r($objects);
            $result = $this->product->create($data_insert);
            //$this->product->update_code_category();
            $this->product->update_code_category();
            //@unlink($file_path);
            //redirect('admin/product');
            //return;
        }

        if (count($data_update) > 0) {  //print_r($objects);
            $result = $this->product->update_multiple($data_update);
            $this->product->update_code_category();
            //$this->product->update_code_category();
            //@unlink($file_path);
            //redirect('admin/product');
            //return;
        }

        @unlink($file_path);
        /*
          echo '<strong>INSERT:</strong> <br>';
          print_r($data_insert);

          echo '<br><br><br><strong>Update:</strong> <br>';
          print_r($data_update);

          echo '<br><br><br><strong>San pham bi trung ma :</strong> <br>';
          print_r($duplicate_error);

          echo '<br><br><br><strong>Privider :</strong> <br>';
          print_r($provider_error);
         */
        redirect('admin/product/view/');

        /* foreach( $books as $book )
          {
          $authors = $book->getElementsByTagName( "author" );
          $author = $authors->item(0)->nodeValue;
         */
    }

    function _create_product_from_xml() {
        //echo 'ABC' == 'Abc' ? 'ABC Abc Bang' : 'ABC != Abc' . '<br>';
        $this->load->library('form_validation');

        $this->form_validation->set_rules('category', 'category', 'callback_category_check');

        $image_upload = $this->upload_image('file', TMP_PATH /* './Data/Tmp/' */, 'xml');

        $error_message = ''; //$image_upload['message'];

        if ($this->form_validation->run() == FALSE OR $image_upload['error'] == true) {
            $data = array();
            //$data['error_message'] = '';
            if ($image_upload['error'])
                $error_message = $image_upload['message'];
            $data['ddlCategory'] = $this->buidDDProductCategoryList('category', '');
            $data['error_message'] = '<div style="color:red">' . validation_errors() . $error_message . '</div>';
            $this->main = $this->load->view('admin/product/form_upload_xml', $data, true);
            $this->execute();
            return;
        }

        $provider_error = array();
        $unit_error = array();
        $duplicate_error = array();
        $data_insert = array();
        $data_update = array();

        $code_pcategory = trim($this->input->post('category'));
        $file_path = TMP_PATH . $image_upload['upload_data']['file_name'];

        if (/* isset($_FILES['file']['tmp_name']) */ file_exists($file_path)) {
            $this->load->helper('text');
            $doc = new DOMDocument();
            $doc->load($file_path /* './Data/Demo_demo.xml' */);
            $sheets = $doc->getElementsByTagName("Worksheet");
            $data = array();

            //$categories2 = $this->category->getAll();
            $this->load->model('pcategory_model', 'pcategory', true);
            $categories = $categories2 = $this->pcategory->getAll();

            $tmp = array();
            for ($i = 0; $i < count($categories2); $i++) {
                $category = $categories2[$i];
                //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
                $tmp[$category->code_parent][$category->code] = $category;
            }

            // Fillter sheets:
            $codes_cat = $this->helpViewProduct($tmp, $code_pcategory);
            $codes_cat[] = $this->db->escape($code_pcategory);
            // Kiem tra Ma danh muc san pham (ten sheet)  co trong database hay ko:
            $pcategory_invalid = array();
            foreach ($sheets as $sheet) {
                $name_sheet = $sheet->getAttribute('ss:Name');
                if (substr(trim($name_sheet), 0, 4) == 'GET-') {
                    $data[] = $sheet;
                    $sheet_name = $sheet->getAttribute('ss:Name');
                    $sheet_name = substr($sheet_name, 4, strlen($sheet_name) - 4); // 4 = strlen('GET-')
                    if (!in_array($this->db->escape($sheet_name), $codes_cat)) {
                        $pcategory_invalid[] = $sheet_name;
                    }
                }
            }
            if (count($pcategory_invalid) > 0) {
                $m = 'Danh muc ' . implode(',', $pcategory_invalid) . ' trong file du lieu khong ton tai trong database hoac khong phu hop voi danh muc <strong>' . $code_pcategory . '</strong>.<br>';

                $data['ddlCategory'] = $this->buidDDProductCategoryList('category', '');
                $data['error_message'] = '<div style="color:red">' . $m . '</div>';
                $this->main = $this->load->view('admin/product/form_upload_xml', $data, true);
                $this->execute();
                return;
            }

            // end fillter sheet.

            $this->load->model('unit_model', 'unit', true);
            $units = $this->unit->getAll();
            $tmp = array();
            for ($i = 0; $i < count($units); $i++) {
                $tmp[trim($units[$i]->vi_name)] = $units[$i];
            }
            $units = $tmp;

            $this->load->model('source_model', 'source', true);
            $sources = $this->source->getAll();
            $tmp = array();
            for ($i = 0; $i < count($sources); $i++) {
                $tmp[trim($sources[$i]->vi_name)] = $sources[$i];
            }
            $sources = $tmp;
            //print_r($sources);

            $this->load->model('provider_model', 'provider', true);
            $providers = $this->provider->getAll();
            $tmp = array();
            for ($i = 0; $i < count($providers); $i++) {
                $tmp[trim($providers[$i]->vi_name)] = $providers[$i];
            }
            $providers = $tmp;
            //print_r($providers);


            $tmp = array();
            for ($i = 0; $i < count($categories); $i++) {
                $tmp[$categories[$i]->code] = $categories[$i];
            }
            $categories = $tmp;

            $this->load->model('product_model', 'product', true);
            $products = $this->product->getAllByCodes($codes_cat);
            $tmp = array();
            for ($i = 0; $i < count($products); $i++) {
                $product = $products[$i];
                //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
                $tmp[trim(strtolower($product->code))] = $product;
                //$tmp[] = trim($product->code);
            }
            $products = $tmp;
            //print_r($products);

            for ($i = 0; $i < count($data); $i++) {
                $sheet = $data[$i];
                $sheet_name = $sheet->getAttribute('ss:Name');
                $sheet_name = substr($sheet_name, 4, strlen($sheet_name) - 4);

                $rows = $sheet->getElementsByTagName('Row');
                $index_row = 0;
                $start_row = 11;
                $provider_name = '';
                foreach ($rows as $row) {
                    $code = "";
                    $middle = "";
                    $last = "";

                    $index = 1;

                    $cells = $row->getElementsByTagName('Cell');

                    if ($cells->item(0)
                            AND $cells->item(1)
                            AND $cells->item(2)
                            AND $cells->item(3)
                            AND $cells->item(4)
                            AND $cells->item(5)
                            AND $cells->item(6)
                            AND $cells->item(7)
                            AND $cells->item(8)
                            AND $cells->item(0)->nodeValue != ''
                            AND $cells->item(1)->nodeValue != ''
                            AND $cells->item(2)->nodeValue != ''
                            AND $cells->item(3)->nodeValue != ''
                            AND $cells->item(4)->nodeValue != ''
                            AND $cells->item(5)->nodeValue != ''
                            AND $cells->item(6)->nodeValue != ''
                            AND $cells->item(7)->nodeValue != ''
                            AND $cells->item(8)->nodeValue != ''
                            AND $index_row >= $start_row
                    ) {

                        // start create product object:
                        $obj = new stdClass();
                        //$obj->code = '';
                        $obj->id_pcategory = 0;
                        $obj->code_pcategory = $sheet_name;

                        $obj->active = 1;
                        $obj->special = 0;
                        $obj->code = trim($cells->item(1)->nodeValue);
                        $obj->vi_name = trim($cells->item(2)->nodeValue);
                        $obj->en_name = trim($cells->item(2)->nodeValue);
                        $obj->vi_description = trim($cells->item(8)->nodeValue);
                        $obj->en_description = trim($cells->item(8)->nodeValue);
                        $unit_name = trim($cells->item(4)->nodeValue);
                        $source_name = trim($cells->item(3)->nodeValue);
                        //$provider_name = trim($cells->item(3)->nodeValue);
                        //echo $unit_name . '_' . $source_name .'<br>';
                        if (array_key_exists(strtolower($unit_name), $units)) {
                            $obj->id_unit = $units[strtolower($unit_name)]->id;
                        } else {

                            $tmp_unit = new stdClass();
                            $tmp_unit->vi_name = $unit_name;
                            $tmp_unit->en_name = $unit_name;
                            $id_unit = $this->unit->insert($tmp_unit);
                            if (!$id_unit)
                                break;
                            $obj->id_unit = $id_unit;
                            //$units = $this->unit->getAll();
                            $tmp_unit->id = $id_unit;
                            $units[strtolower($unit_name)] = $tmp_unit;
                            /* $tmp =  array();
                              for($i = 0; $i < count($units); $i++){
                              $tmp[$units[$i]->vi_name] = $units[$i];
                              }
                              $units = $tmp; */
                        }


                        if (array_key_exists(($source_name), $sources)) {
                            $obj->id_source = $sources[$source_name]->id;
                        } else {
                            $obj->id_source = 0;

                            $tmp_source = new stdClass();
                            $tmp_source->vi_name = $source_name;
                            $tmp_source->en_name = $source_name;
                            $id_source = $this->source->insert($tmp_source);
                            if (!$id_source > 0) {
                                $index_row++;
                                continue;
                            }
                            $obj->id_source = $id_source;
                            $tmp_source->id = $id_source;
                            $sources[$source_name] = $tmp_source;
                        }

                        if (array_key_exists($provider_name, $providers)) {
                            $obj->id_provider = $providers[$provider_name]->id_provider;
                        } else {
                            $obj->id_provider = 0;
                            //$index_row++;
                            //continue;
                            //$provider_error[] = $provider_name;
                        }



                        $obj->quantity = trim($cells->item(5)->nodeValue);
                        $obj->price = trim($cells->item(6)->nodeValue);
                        $obj->image = PRODUCT_IMAGE_PATH . $obj->code . PRODUCT_IMAGE_EXT;
                        $obj->date_add = date('Y-m-d H:i:s', time());
                        $obj->date_upd = date('Y-m-d H:i:s', time());

                        //if($obj->code!='' AND $obj->code!=null AND $obj->vi_name!='' AND $obj->vi_name!=null)
                        //	$objects[] = $obj;

                        if (array_key_exists(trim(strtolower($obj->code)), $products)) {
                            if (array_key_exists(trim(strtolower($obj->code)), $data_update)) {
                                $duplicate_error[] = $obj->code;
                            }
                            else
                                $data_update[trim(strtolower($obj->code))] = $obj;
                        }
                        else {
                            if (array_key_exists(trim(strtolower($obj->code)), $data_insert)) {
                                $duplicate_error[] = $obj->code;
                            }
                            else
                                $data_insert[trim(strtolower($obj->code))] = $obj;
                            //echo trim(strtolower($obj->code)) . '  _____  <br>' . ;
                        }

                        /*
                          if(in_array(trim($obj->code), $products)){
                          //if()
                          $data_update[trim($obj->code)] = $obj;
                          }
                          else{
                          $data_insert[trim($obj->code)] = $obj;
                          }
                         */
                        // end create product object
                    }
                    elseif ($cells->item(0) AND $cells->item(1) == null AND $cells->item(2) == null AND $cells->item(3) == null AND $cells->item(4) == null AND $cells->item(5) == null AND $cells->item(6) == null AND $cells->item(7) == null AND $cells->item(8) == null) {
                        if (array_key_exists(trim(($cells->item(0)->nodeValue)), $providers)) {
                            $provider_name = trim($cells->item(0)->nodeValue);

                            //echo '<b>' . $cells->item(0)->nodeValue . '</b><br>';
                        } else {
                            //$provider_error[] = trim($cells->item(0)->nodeValue);
                            $index_row++;
                            continue;
                            //$provider_error[] = $provider_name;
                        }

                        //echo  $cells->item(2)->nodeValue();
                    }
                    $index_row++;
                }
            }
        } else {

        }

        if (count($data_insert) > 0) {  //print_r($objects);
            $result = $this->product->create($data_insert);
            //$this->product->update_code_category();
            $this->product->update_code_category();
            //@unlink($file_path);
            //redirect('admin/product');
            //return;
        }

        if (count($data_update) > 0) {  //print_r($objects);
            $result = $this->product->update_multiple($data_update);
            //$this->product->update_code_category();
            //$this->product->update_code_category();
            //@unlink($file_path);
            //redirect('admin/product');
            //return;
        }

        @unlink($file_path);
        /*
          echo '<strong>INSERT:</strong> <br>';
          print_r($data_insert);

          echo '<br><br><br><strong>Update:</strong> <br>';
          print_r($data_update);

          echo '<br><br><br><strong>San pham bi trung ma :</strong> <br>';
          print_r($duplicate_error);

          echo '<br><br><br><strong>Privider :</strong> <br>';
          print_r($provider_error);
         */
        redirect('admin/product/view/');

        /* foreach( $books as $book )
          {
          $authors = $book->getElementsByTagName( "author" );
          $author = $authors->item(0)->nodeValue;
         */
    }

    function read1() {


        $dom = DOMDocument::load('./Data/Demo_demo.xml');
        $sheets = $dom->getElementsByTagName('Worksheet');

        foreach ($sheets as $sheet) {
            echo $sheet->getAttribute('Name');
        }
        //print_r($sheets);
        //echo '<br><br>';

        $rows = $dom->getElementsByTagName('Row');
        $first_row = true;

        foreach ($rows as $row) {

            $first = "";
            $middle = "";
            $last = "";
            //print_r($row);
            $index = 1;
            $cells = $row->getElementsByTagName('Cell');
            foreach ($cells as $cell) {
                $ind = $cell->getAttribute('Index');
                if ($ind != null)
                    $index = $ind;

                if ($index == 1)
                    $first = $cell->nodeValue;
                if ($index == 2)
                    $middle = $cell->nodeValue;
                if ($index == 3)
                    $last = $cell->nodeValue;

                $index += 1;
            }
            echo $first . '    ' . $middle . '    ' . $last . '<br>';
        }
    }

    function category_check($category) {
        if (trim($category) == '0' || trim($category) == '') {
            $this->form_validation->set_message('category_check', lang('none_selected_category'));
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function helpViewProduct($tmp, $parent = '') {
        $result = array();

        if (isset($tmp[$parent])) {
            $num_record = count($tmp[$parent]);
            foreach ($tmp[$parent] as $k => $v) {
                $parent = $v->code;
                $value = $v->code;

                $result[] = $this->db->escape($v->code);

                $result = array_merge($result, $this->helpViewProduct($tmp, $parent));
            }
        }

        return $result;
    }

}

?>
